package svc

import (
	_ "github.com/go-sql-driver/mysql"
	"group-card/common/tool"
	cardmodel2 "group-card/model/cardmodel"
	"group-card/model/entity"
	"group-card/rpc/card/internal/config"
	"time"
	"xorm.io/core"
	"xorm.io/xorm"
)

type ServiceContext struct {
	Config            config.Config
	Orm               *xorm.Engine
	SkinModel         cardmodel2.CardSkinModel
	PublishModel      cardmodel2.CardPublishModel
	BindingModel      cardmodel2.CardBindingModel
	TraceabilityModel cardmodel2.CardTraceabilityModel
}

func NewServiceContext(c config.Config) *ServiceContext {

	//sqlConn := sqlx.NewMysql(c.Mysql.Datasource) // 连接数据库
	Orm, err := xorm.NewEngine(c.Mysql.DriverName, c.Mysql.Datasource)
	if err != nil {
		tool.GLogLine("mysql数据库连接失败", err)
	}
	//连接测试
	if err := Orm.Ping(); err != nil {
		tool.GLogLine("mysql数据库连接失败", err)
	}
	//日志打印SQL
	Orm.ShowSQL(true)
	//设置连接池的空闲数大小
	Orm.SetMaxIdleConns(100)
	//设置最大打开连接数
	Orm.SetMaxOpenConns(500)
	//名称映射规则主要负责结构体名称到表名和结构体field到表字段的名称映射
	Orm.SetTableMapper(core.SnakeMapper{})
	Orm.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	//连接成功
	tool.GLogLine("mysql数据库连接成功")

	err = Orm.Sync2(
		new(entity.CardSkin),
		new(entity.CardPublish),
		new(entity.CardBinding),
		new(entity.CardTraceability),
	)
	if err != nil {
		tool.GLogLine("生成表失败:", err)
	}

	return &ServiceContext{
		Config:            c,
		Orm:               Orm,
		SkinModel:         cardmodel2.NewCardSkinModel(Orm),
		PublishModel:      cardmodel2.NewCardPublishModel(Orm),
		BindingModel:      cardmodel2.NewCardBindingModel(Orm),
		TraceabilityModel: cardmodel2.NewCardTraceabilityModel(Orm),
	}
}
